import React from 'react';
import { Select, Cascader, Form, Input } from 'antd';
import moment from 'moment';
import _, { isArray } from 'lodash';
import constantModel from '@/utils/constantModel';
import { Meta } from '@/components/schema-form-render/meta';
import { switchComp } from './switchComp';

interface PropsCompProps {
    propsCascadeOptions?: any[];
    dataOperatorOptions: any[];
    onChange?: any;
    value?: any;
}

interface PropsCompState {
    value: any | null;
}

class PropsComp extends React.PureComponent<PropsCompProps, PropsCompState> {
    form: any = React.createRef();
    state = {
        value: null,
    };
    componentDidMount() {
        this.initData(this.props)
    }
    componentWillReceiveProps(nextProps: Readonly<PropsCompProps>) {
        this.initData(nextProps)
    }

    initData = (props: PropsCompProps) => {
        const form = this.form.current;
        const { value, propsCascadeOptions } = props;
        // 有初始值
        // @ts-ignore
        if (value && !this.state.value && propsCascadeOptions?.length > 0) {
            let parent: any = {};
            const cascaderValueArr = value?.cascaderValue.map((key: string, index: number) => {
                if (index === 0) {
                    parent = _.find(propsCascadeOptions, o => o.key === key);
                    return parent;
                }
                return _.find(parent.children, m => m.key === key);
            });

            const currentProps: Meta = cascaderValueArr.slice(-1)[0];
            if (currentProps) {
                this.handleCompExtraProps(currentProps, currentProps.props.inputValueComponentType, value);
            }
            const mapValue = this.handleFormatMapCompInit(
                value?.cascaderMapValue,
                currentProps?.props?.inputValueComponentType,
                value?.cascaderMapValueProps.itemDesc,
                currentProps?.props,
            );

            this.setState(
                {
                    value: {
                        cascaderValue: cascaderValueArr,
                        dataOPValue: value?.dataOPValue,
                        cascaderMapValue: mapValue,
                    },
                },
                () => {
                    form.setFieldsValue({
                        cascaderValueShow: value?.cascaderValue,
                        dataOPValueShow: value?.dataOPValue,
                        cascaderMapValueShow: mapValue,
                    });
                },
            );
        }
    }

    // 属性变更
    handlePropsChange = (e: any, row: any) => {
        const { value } = this.state;
        const form = this.form.current;
        let opValue: any = {};
        if (value) {
            opValue = _.cloneDeep(value);
        }

        // 设置属性值
        opValue.cascaderValue = row;
        opValue.cascaderMapValue = '';
        form.setFieldsValue({
            cascaderMapValueShow: '',
        });
        this.triggerChange(opValue);
    };

    // 触发change
    triggerChange = (value: any) => {
        const { onChange } = this.props;
        this.setState(
            {
                value,
            },
            () => {
                onChange(value);
            },
        );
    };

    // 操作符号变更
    handleDataOpChange = (e: any, row: any) => {
        const { value } = this.state;
        let opValue: any = {};
        if (value) {
            opValue = _.cloneDeep(value);
        }
        // 设置操作符
        opValue.dataOPValue = row;
        opValue.dataOPValueShow = e;
        this.triggerChange(opValue);
    };

    // 处理不同组件对应的值
    handleFormatMapCompValue = (e: any, type: string, row: any) => {
        const { value } = this.state;

        switch (type) {
            case 'DATE_V1':
            case 'SELECT':
            case 'User_SELECT_TABEL':
            case 'NUMBER': {
                return e;
            }
            case 'BIZ_SELECT':
            case 'BIZ_TREE_SELECT': {
                if (isArray(e)) {
                    return e.join(',')
                } else {
                    return e
                }
            }
            default:
                return e.target.value;
        }
    };

    // 初始化不同组件对应的值
    handleFormatMapCompInit = (e: any, type: any, itemDesc: any, currentProps?: any) => {
        switch (type) {
            case 'BIZ_SELECT':
            case 'BIZ_TREE_SELECT':
                if (e.includes(',') && typeof e === 'string') {
                    return e.split(',')
                }
            default:
                return e;
        }
    };

    // 针对不同的组件的额外属性处理
    handleCompExtraProps = (cProps: Meta, type: any, value: any) => {
        switch (type) {
            case 'ORG_EMP_SELECTOR_MULT':
                cProps.props.inputDefaultValue = value.cascaderMapValueProps.itemDesc;
                break;
            default:
                break;
        }
    };

    // 属性对应值变更
    handleValueChange = (e: any, type: any, data: any) => {
        const val = this.handleFormatMapCompValue(e, type, data);
        const { value } = this.state;
        let opValue: any = {};
        if (value) {
            opValue = _.cloneDeep(value);
        }
        // 设置属性对应值
        opValue.cascaderMapValue = val;
        this.triggerChange(opValue);
    };

    // 获取当前属性对应录入组件
    getCurrentValueComp = (props: any) => {
        const { value }: any = this.state;
        // 如果存在属性
        if (
            // @ts-ignore
            value?.cascaderValue?.length > 0
        ) {
            // 获取最后一个值
            // @ts-ignore
            // return <Input />;

            const currentProps: Meta = value.cascaderValue.slice(-1)[0];
            if (!currentProps) return null
            console.log('currentProps', currentProps)
            currentProps.props.value = value?.cascaderMapValue || ''
            // const currentProps: any = {
            //   props: {}
            // }
            currentProps.props.onChange = (e: any, data: any) =>
                this.handleValueChange(e, currentProps.props.inputValueComponentType, data);
            return switchComp({
                ...currentProps.props,
                ...currentProps.props?.attributes

            }, currentProps.props.inputValueComponentType);
        }
        return null;
    };

    render() {
        const {
            propsCascadeOptions = [],
            dataOperatorOptions = [],
        } = this.props;
        const { value } = this.state;

        return (
            <Form ref={this.form} style={{ display: 'flex', flexWrap: 'nowrap' }}>
                <Form.Item name="cascaderValueShow" key="cascaderValueShow">
                    <Cascader
                        fieldNames={{
                            label: 'label',
                            value: 'key',
                        }}
                        style={{
                            marginRight: 10,
                        }}
                        onChange={this.handlePropsChange}
                        options={propsCascadeOptions}
                    />
                </Form.Item>
                <Form.Item name="dataOPValueShow" key="dataOPValueShow">
                    {
                        <Select
                            style={{
                                width: 80,
                                marginRight: 10,
                            }}
                            onChange={this.handleDataOpChange}
                        >
                            {dataOperatorOptions}
                        </Select>
                    }
                </Form.Item>
                {// @ts-ignore
                    value?.cascaderValue?.length > 0 && (
                        <Form.Item name="cascaderMapValueShow" key='cascaderMapValueShow' style={{ marginRight: 10, width: 184 }}>
                            {(this.getCurrentValueComp())}
                        </Form.Item>
                    )}
            </Form>
        );
    }
}

export default PropsComp
